﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;

namespace SBPweb.PROvibe.Server.Library.Hosting
{

    public class CustomServiceHostFactory : ServiceHostFactoryBase
    {

        static CustomServiceHostFactory()
        {
            ServiceHosts = new ConcurrentDictionary<string, ServiceHostBase>();
        }

        public static ConcurrentDictionary<string, ServiceHostBase> ServiceHosts
        {
            get;
            private set;
        }
        
        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            string match = "dynamic";
            string path = baseAddresses.FirstOrDefault().PathAndQuery;
            path = path.Substring(path.LastIndexOf(match, StringComparison.InvariantCultureIgnoreCase) + match.Length + 1);
            ServiceHostBase host = ServiceHosts.FirstOrDefault(x => x.Key.Equals(path, StringComparison.InvariantCultureIgnoreCase)).Value;
            if (host == null)
            {
                throw new System.Web.HttpException(404, "Service Host not found");
            }
            return host;
        }

    }

}